package com.azthink.chapter423.handler;

//全局异常处理类（统一的异常处理，捕获到的异常是controller的异常）

import com.azthink.chapter423.utils.ResultGenerator;
import com.azthink.chapter423.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger("GlobalExceptionHandler");

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<String> defaultExceptionHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws Exception {
        logger.error("DefaultException Handler Host: {} invokes url: {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), e.getMessage());
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            resp.setStatus(404);
            return ResultGenerator.fail404(req.getRequestURI());
        } else if (e instanceof AuthException) {
            resp.setStatus(Result.RESULT_CODE_UNAUTHORIZED);
            return ResultGenerator.unauthorized(e.getMessage());
        } else {
            resp.setStatus(500);//设置Http响应吗
            return ResultGenerator.fail500(e.getMessage());
        }

    }

}
